package com.kun.music.controller;

import com.alibaba.fastjson.JSONObject;
import com.kun.music.domain.Collect;
import com.kun.music.service.CollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author fangkun
 * @create 2023-01-04-11:43
 */
@RestController
public class CollectController {

    @Autowired
    private CollectService collectService;

    @GetMapping("/collection/detail")
    public Object userCollection(@RequestParam("userId") int userId){
        return collectService.userCollection(userId);
    }

    @GetMapping("/collection/delete")
    public Object deleteUserCollect(@RequestParam("userId") int userId, @RequestParam("songId") int songId){
        JSONObject jsonObject = new JSONObject();

        boolean res = collectService.deleteUserCollect(userId,songId);

        if (res){
            jsonObject.put("code",1);
            jsonObject.put("msg","删除成功！");
            return jsonObject;
        } else {
            jsonObject.put("code",0);
            jsonObject.put("msg","删除失败！");
            return jsonObject;
        }
    }

    @PostMapping(value = "/collection/add")
    public Object addCollection(HttpServletRequest req){
        JSONObject jsonObject = new JSONObject();

        String user_id = req.getParameter("userId");
        String type = req.getParameter("type");
        String song_id=req.getParameter("songId");
        String song_list_id=req.getParameter("songListId");

        if (song_id == ""){
            jsonObject.put("code", 0);
            jsonObject.put("msg", "收藏歌曲为空");
            return jsonObject;
        } else if (collectService.existSongId(Integer.parseInt(user_id), Integer.parseInt(song_id))) {
            jsonObject.put("code", 2);
            jsonObject.put("msg", "已收藏");
            return jsonObject;
        }

        Collect collect = new Collect();
        collect.setUserId(Integer.parseInt(user_id));
        collect.setType(new Byte(type));
        if (new Byte(type) == 0) {
            collect.setSongId(Integer.parseInt(song_id));
        } else if (new Byte(type) == 1) {
            collect.setSongListId(Integer.parseInt(song_list_id));
        }
        collect.setCreateTime(new Date());

        boolean res = collectService.addCollection(collect);
        if (res){
            jsonObject.put("code", 1);
            jsonObject.put("msg", "收藏成功");
            return jsonObject;
        }else {
            jsonObject.put("code", 0);
            jsonObject.put("msg", "收藏失败");
            return jsonObject;
        }
    }

}
